package com.mrlv.rabbitmq;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 多线程之间顺序调用， A -> B -> C
 * AA打印5次 BB打印10次 CC打印15次 循环10轮
 * @author Mrlv
 * @date 2021年11月18日 10:04
 * @version 1.0
 */
public class ThreadOrderAccess {

    public static void main(String[] args) {
        PrintCode printCode = new PrintCode();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) { printCode.printA(); }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) { printCode.printB(); }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) { printCode.printC(); }
        }).start();

    }




}

class PrintCode {

    private int number = 1;

    private Lock lock = new ReentrantLock();


    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            while (number != 1) {
                conditionA.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println("AA");
            }
            number = 2;
            conditionB.signal();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void printB() {
        lock.lock();
        try {
            while (number != 2) {
                conditionB.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("BB");
            }
            number = 3;
            conditionC.signal();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (number != 3) {
                conditionC.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println("CC");
            }
            number = 1;
            conditionA.signal();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}